<template>
  <div class="app-container">
    <el-card>
      <el-button
        icon="el-icon-plus"
        type="primary"
        size="small"
        @click="addHandle"
      />
      <el-table border stripe :data="list">
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="名字" prop="name" align="center" />
        <!-- 商品分类 -->
        <el-table-column label="分类" align="center">
          <template slot-scope="scope">
            <span>{{
              scope.row.category ? scope.row.category.name : '暂无分类'
            }}</span></template
          ></el-table-column
        >
        <!-- 主图 -->
        <el-table-column label="主图" align="center">
          <template slot-scope="scope">
            <img
              :src="scope.row.coverImage | dalImg"
              style="max-width: 120px"
            /> </template
        ></el-table-column>
        <el-table-column label="价格" prop="price" align="center" />
        <el-table-column label="库存" prop="amount" align="center" />
        <!-- <el-table-column label="简介" prop="desc" align="center" /> -->
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editHandle(scope.row)"
            />
            <el-popconfirm
              title="是否确认删除？"
              @onConfirm="delHandle(scope.row)"
            >
              <el-button
                style="margin-left: 8px"
                slot="reference"
                type="danger"
                size="mini"
                icon="el-icon-delete"
              />
            </el-popconfirm> </template></el-table-column
      ></el-table>
      <!-- 分页器 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        @current-change="loadData"
      />
    </el-card>
  </div>
</template>

<script>
import { loadModelsAPI, delModelByIdAPI } from '@/api/products'
export default {
  data() {
    return {
      list: [],
      total: 0
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 修改商品
    editHandle(item) {
      // console.log(item)
      this.$router.push({
        name: 'ProductEdit',
        query: {
          id: item.id
        }
      })
    },
    // 删除商品
    async delHandle(item) {
      // console.log(item)
      await delModelByIdAPI(item.id)
      this.loadData()
    },
    // 加载数据
    async loadData(page = 1) {
      const res = await loadModelsAPI(page)
      this.list = res.data
      this.total = res.total
    },
    addHandle() {
      this.$router.push({
        name: 'ProductEdit'
      })
    }
  }
}
</script>

<style></style>
